package com.woniu.gf.pawn.comm.core.util;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

public class OssUntil {


    // endpoint 访问OSS的域名
    private static String endPoint = "http://oss-cn-chengdu.aliyuncs.com";

    // accessKeyId和accessKeySecret OSS的访问密钥
    private static String accessKeyId = "LTAI4G9gyMb1RWpRWHF4isba";
    private static String accessKeySecret = "OmU0Zf70tEC4ps3L8rqEXC5an0aWgq";

    // Bucket 用来管理所存储Object的存储空间
    private static String bucketName = "qft98";

    //URL
    private static String URL="https://qft98.oss-cn-chengdu.aliyuncs.com/";

    /**
     * 获取oss连接
     * @return
     */
    public static OSSClient getOssClient(){
        OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
        if(ossClient.doesBucketExist(bucketName)){
            return ossClient;
        }
        return null;
    }

    /**
     * 删除图片
     * @param url
     */
    public static void deleteObject(String url){
        OSSClient ossClient = getOssClient();
        Optional<String> optional = Optional.of(url);
        try{
            if(optional.isPresent()){
                    ossClient.deleteObject(bucketName,url.replace("https://qft98.oss-cn-chengdu.aliyuncs.com/",""));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(ossClient!=null) ossClient.shutdown();
        }

    }

    /**
     * 上传图片
     * @param files
     * @return 返回图片地址集合
     * @throws IOException
     */

    public static List<String> putObject(List<MultipartFile> files)  {
        //获取oss的连接
        OSSClient ossClient = getOssClient();
        Optional<List<MultipartFile>> optional = Optional.of(files);
        List<String>  urls=new ArrayList<>();
        try{
            if(optional.isPresent()) {
                for (MultipartFile file : files) {
                    //获取图片输入流
                    InputStream inputStream = file.getInputStream();
                    //获取上传图片的名字
                    String filename = file.getOriginalFilename();
                    //生成图片名字 防止图片名字重复
                   filename = UUID.randomUUID().toString().replace("-", "")+filename.substring(filename.lastIndexOf("."));
                    //上传
                    PutObjectResult putObjectResult = ossClient.putObject(bucketName, "image/" + filename, inputStream);

                    urls.add(URL+"image/" + filename);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(ossClient!=null) ossClient.shutdown();
        }
        return urls;
    }

}
